import { Injectable, NotFoundException } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { isNil } from 'lodash'
import { Repository } from 'typeorm'
import { paginate } from '~/helper/paginate'
import { Pagination } from '~/helper/paginate/pagination'
import { CreateMovieDto } from '../dto/create-movie.dto'
import { QueryMovieDto } from '../dto/query-movie.dto'
import { UpdateMovieDto } from '../dto/update-movie.dto'
import { MovieEntity } from '../entities/movie.entity'
import { VideoTagEntity } from '../entities/video-tag.entity'

@Injectable()
export class MovieService {
  constructor(
    @InjectRepository(MovieEntity)
    private readonly movieRepository: Repository<MovieEntity>,
    @InjectRepository(VideoTagEntity)
    private readonly videoTagRepository: Repository<VideoTagEntity>,
  ) {}

  /**
   * 创建影片
   */
  async create(createMovieDto: CreateMovieDto) {
    const movie = this.movieRepository.create(createMovieDto)
    return this.movieRepository.save(movie)
  }

  /**
   * 查询影片列表（分页）
   */
  async findAll(query: QueryMovieDto): Promise<Pagination<MovieEntity>> {
    const { page, pageSize, videoName, videoGrade, tagId } = query

    const queryBuilder = this.movieRepository
      .createQueryBuilder('movie')
      .leftJoinAndSelect('c_video_tag', 'tag', 'movie.videoTagId = tag.id')
      .where('movie.isDelete = :isDelete', { isDelete: 0 })

    // 添加筛选条件
    if (videoName) {
      queryBuilder.andWhere('movie.videoName LIKE :videoName', { videoName: `%${videoName}%` })
    }

    if (!isNil(videoGrade)) {
      queryBuilder.andWhere('movie.videoGrade = :videoGrade', { videoGrade })
    }

    if (!isNil(tagId)) {
      queryBuilder.andWhere('movie.videoTagId = :tagId', { tagId })
    }

    // 设置需要查询的标签字段
    queryBuilder.addSelect([
      'tag.tag_name as tagName',
    ])

    // 设置默认排序
    queryBuilder.orderBy('movie.createdAt', 'DESC')

    return paginate<MovieEntity>(queryBuilder, {
      page,
      pageSize,
    })
  }

  /**
   * 查询单个影片
   */
  async findOne(id: number) {
    const movie = await this.movieRepository
      .createQueryBuilder('movie')
      .leftJoinAndSelect('c_video_tag', 'tag', 'movie.videoTagId = tag.id')
      .where('movie.id = :id', { id })
      .andWhere('movie.isDelete = :isDelete', { isDelete: 0 })
      .addSelect(['tag.tag_name as tagName'])
      .getOne()

    if (!movie) {
      throw new NotFoundException(`影片ID为${id}的记录不存在`)
    }

    return movie
  }

  /**
   * 更新影片信息
   */
  async update(id: number, updateMovieDto: UpdateMovieDto) {
    const movie = await this.findOne(id)

    return this.movieRepository.save({
      ...movie,
      ...updateMovieDto,
    })
  }

  /**
   * 删除影片（逻辑删除）
   */
  async remove(id: number) {
    const movie = await this.findOne(id)

    // 逻辑删除
    movie.isDelete = 1

    return this.movieRepository.save(movie)
  }
}
